package elitech.vietnam.weatherfashion.tabs.settings;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.ConfirmDialog;
import elitech.vietnam.weatherfashion.dialog.DialogUserInfo;
import elitech.vietnam.weatherfashion.dialog.MyProgressDialog;
import elitech.vietnam.weatherfashion.dto.FriendDTO;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.BaseContainerFragment;
import elitech.vietnam.weatherfashion.tabs.styler.StylerDetailFragment;

public class AdapterFriendListListView extends ArrayAdapter<FriendDTO> {

	public static final String BROADCAST_DELETED = "elitech.vietnam.weatherfashion.backgroundtask.ReloadTodayDataService";

	private ArrayList<FriendDTO> objects;
	private Context context;
	private MyProgressDialog mProgressDialog;
	// private final Lock lock = new ReentrantLock();
	private ItemFriendList view;
	private Intent intent;

	boolean isAddMeList;

	public AdapterFriendListListView(Context context, ArrayList<FriendDTO> listFriend, boolean isAddMeList) {
		super(context, R.layout.item_setting_friend_list, listFriend);
		this.objects = listFriend;
		this.context = context;
		this.isAddMeList = isAddMeList;

		intent = new Intent(BROADCAST_DELETED);

		mProgressDialog = new MyProgressDialog(context);
		mProgressDialog.setCancelable(false);
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		view = (ItemFriendList) convertView;

		if (view == null) {
			view = new ItemFriendList(context);
		}

		try {
			// lock.lock();
			final FriendDTO friend = objects.get(position);
			// lock.unlock();

			if (friend != null) {
				if (friend.getFriendPic() == null || friend.getFriendPic().equals("")) {
					view.imageViewAvatar.setImageResource(R.drawable.avatar);
				} else {
					String imageUrl = Const.SERVER_IMAGE_URL + friend.getFriendPic();
					UrlImageViewHelper.setUrlDrawable(view.imageViewAvatar, imageUrl);
				}

				OnClickListener itemClick = new OnClickListener() {
					@Override
					public void onClick(View v) {
						MemberDTO member = new MemberDTO();
						member.setMemberUsername(friend.getFriendUsername());
						member.setMemberPic(friend.getFriendPic());
						member.setMemberName(friend.getFriendName());
						member.setMemberProfile(friend.getFriendProfile());
						new DialogUserInfo(context, member).show();
					}
				};

				OnClickListener itemClick1 = new OnClickListener() {
					@Override
					public void onClick(View v) {
						BaseContainerFragment base = ((MainActivity) context).getCurrentBase();
						if (base != null)
							base.replaceFragment(StylerDetailFragment.init(friend.getFriendId()), true);
					}
				};

				view.imageViewAvatar.setOnClickListener(itemClick);

				String line1 = friend.getFriendName() + " (" + friend.getFriendUsername() + ")";
				view.tvMemberName.setText(line1);
				view.tvMemberName.setOnClickListener(itemClick1);
				view.tvFriendProfile.setText(friend.getFriendProfile());
				view.tvFriendProfile.setOnClickListener(itemClick1);
				view.btnXoaBanBe.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						view.btnXoaBanBe.setEnabled(false);
						new ConfirmDialog.Builder(getContext())
						.setMessage(getString(R.string.setting_delete_friend_message_confirm))
						.setYesClick(new ConfirmDialog.OnYesClick() {
							@Override
							public void doClick() {
								MemberDTO user = GlobalValue.getInstance(getContext()).readUserInfo();
								DeleteFriendAsynTask deleteFriend = new DeleteFriendAsynTask();
								deleteFriend.execute(user.getId(), friend.getFriendId(), position);
							}
						})
						.setNoClick(new ConfirmDialog.OnNoClick() {
							@Override
							public void doClick() {
								view.btnXoaBanBe.setEnabled(true);
							}
						})
						.build().show();
					}
				});
				if (isAddMeList)
					view.btnXoaBanBe.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			// lock.unlock();
		}
		return view;
	}

	private String getString(int idRes) {
		return context.getResources().getString(idRes);
	}

	public ArrayList<FriendDTO> getList() {
		return objects;
	}

	public void reloadData(List<FriendDTO> friends) {
		try {
			// lock.lock();
			objects = (ArrayList<FriendDTO>) friends;
			AdapterFriendListListView.this.notifyDataSetChanged();
		} catch (Exception e) {} finally {
			// lock.unlock();
		}
	}

	public void remove(int position) {
		try {
			// lock.lock();
			objects.remove(position);
			WFApplication.getInstance().userFriends = objects;
			AdapterFriendListListView.this.notifyDataSetChanged();
		} catch (Exception e) {} finally {
			// lock.unlock();
		}
	}

	class ItemFriendList extends LinearLayout {

		public ImageView imageViewAvatar;
		public TextView tvMemberName;
		public TextView tvFriendProfile;
		public Button btnXoaBanBe;
		public LinearLayout itemHead;
		public LinearLayout itemMid;

		public ItemFriendList(Context context) {
			super(context);
			LayoutInflater inflacter = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			inflacter.inflate(R.layout.item_setting_friend_list, this, true);

			imageViewAvatar = (ImageView) this.findViewById(R.id.imageViewAvatar);
			tvMemberName = (TextView) this.findViewById(R.id.tvMemberId);
			tvFriendProfile = (TextView) this.findViewById(R.id.tvFriendProfile);
			btnXoaBanBe = (Button) this.findViewById(R.id.btnXoaBanBe);
		}

	}

	private void showToast(String mess) {
		// Toast.makeText(context, mess, Toast.LENGTH_SHORT).show();
		Toast toast = Toast.makeText(context, mess, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	private class DeleteFriendAsynTask extends AsyncTask<Integer, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Integer... params) {
			int userId = params[0];
			int friendId = params[1];
			final int position = params[2];
			boolean response = true;

			try {
				PHPSoapServiceCaller phpService = new PHPSoapServiceCaller();
				response = phpService.deleteFriend(userId, friendId);

				if (response) {

					((Activity) context).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							remove(position);
						}
					});

					// Reload styler friend
					Utils.getStylerFriendData(getContext());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (result) {
				intent.putExtra("DELETE_DONE", true);
				getContext().sendBroadcast(intent);

				if (WFApplication.getInstance().stylerFriendData != null)
					WFApplication.getInstance().stylerFriendData = null;
				showToast(getString(R.string.setting_delete_friend_success));
			} else {
				showToast(getString(R.string.setting_delete_friend_fail));
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}
	}

}
